<!--
 * 每个菜单对应一个配置项, 注意, 菜单中需要配置一下菜单标识(code), 这样才能通过路径直接
 * 展开指定的配置项
-->
<template>
  <div ref="configElRef">
    <PageWrapper :sidebarWidth="230" ref="contentElRef" content-full-height>
      <template #sidebar>
        <MyTreeSelect 
          v-bind="treeProps" 
          @select="onTreeSelect" 
          @add-child="handleAddGroup"
          @edit="handleEditGroup"
        />
      </template>

      <div class="h-full">
        
        <Spin :spinning="state.loading" size="large" :style="spinStyle">
          <ScrollContainer :style="scrollStyle">
            <MyAlert 
              style="width: 90%"
              type="warning" 
              message="为降低敏感数据泄露的风险，自 2024 年 4 月 21 日起，敏感数据在创建时候要保管好, 后续不可再进行查询(脱敏展示)，请保存敏感数据。"
            />
            <div :class="`${prefixCls}-content`" >
              <BasicTitle :class="`${prefixCls}-title`" v-if="selectNode && selectNode.name" > 
                {{ selectNode.name }}
              </BasicTitle>
              <component 
                style="margin-bottom: 10px;"
                @query-success="handleQuerySuccess"
                v-if="selectNode && selectNode.component" 
                :is="selectNode.component" 
                :key="selectNode.path" 
              />
              <Empty v-else />
            </div>
            
            <!-- <a-button :class="`${prefixCls}-edit-field`" type="primary" block preIcon="ant-design:export-outlined" >配置字段</a-button> -->
          </ScrollContainer>
        </Spin>
      </div>
    </PageWrapper>
  </div>

</template>

<script lang="ts" setup name="system-config-center">
import { PageWrapper } from '/@/components/Page';
import { BasicTitle } from '/@/components/Basic';
import { 
  provide, ref, CSSProperties, onUnmounted, unref, 
  onMounted, toRaw, shallowRef, defineAsyncComponent
} from 'vue'
import { useDesign } from '/@/hooks/web/useDesign'
import MyAlert from '/@/components/My/MyAlert.vue';
import { useModal } from '/@/components/Modal';
import { listChildTree } from '/@/utils/helper/treeHelper';
import { MyTreeSelect, MyTreeProps } from '/@/components/BizTreeSelect';
import { usePermissionStore } from '/@/store/modules/permission';
import { MaterialType } from '/@/components/BizMaterial/src/material.data'
import EXCEPTION_COMPONENT from '/@/views/sys/exception/Exception.vue'
import { ScrollContainer } from '/@/components/Container';
import { useRoute, useRouter } from "vue-router"
import { cloneDeep } from 'lodash-es';

const router = useRouter()
const { configKey } = router.currentRoute.value.query
let dynamicViewsModules: Record<string, () => Promise<Recordable>>;
const activeMaterialType = ref(MaterialType.IMAGE.type)
const contentElRef = ref()
const materialGroupTreeRef = ref<any>()
const [registerModal, { openModal }] = useModal();
const { prefixCls } = useDesign('config-center')
const { flatMenuList } = usePermissionStore()
const menuList = Array.from(cloneDeep(toRaw(flatMenuList)).values())
const defaultSelectConfig = configKey && menuList.find((e, index) =>  e.code === `config_key__${configKey}`)
const childTree = listChildTree(menuList, {
  pid: 'parentId',
  id: 'id',
  children: 'children',
}, (node) => {
  // 匹配配置中心的根路由, 即页面上左侧显示的配置中心菜单路由
  return node.componentName === 'system/configCenter/index.vue'
})

interface SelectNode {
  component?: any;
  path?: string;
  name?: string
}
interface State {
  loading: boolean;
  timer?: any
}
const treeProps = ref<MyTreeProps>({
  treeData: childTree,
  expandedKeys: defaultSelectConfig ? [defaultSelectConfig.id] : [],
  // showLine: false,
  searchField: 'name',
  enableAddChird: false,
  enableDelete: false,
  enableEdit: false
})

const state = ref<State>({
  loading: false
})
const selectNode = shallowRef<SelectNode | undefined>({})
const stateValue = state.value

provide('prefixCls', prefixCls)

const configElRef = ref<HTMLDivElement>();
const scrollStyle: CSSProperties = {
  height: 'calc(100vh - 105px)',
};
const spinStyle = ref<CSSProperties>({
  maxHeight: '100%'
});

onUnmounted(() => {
  clearTimeout(stateValue.timer)
  stateValue.timer = null
})

onMounted(() =>{
  
})


function dynamicImport(component: string) {
  if (!dynamicViewsModules) {
    dynamicViewsModules = import.meta.glob('/src/views/system/configCenter/components/**/*.{vue,tsx}')
  }
  const keys = Object.keys(dynamicViewsModules);
  const matchKeys = keys.filter((key) => {
    const k = key.replace('/src/views', '');
    const startFlag = component.startsWith('/');
    const endFlag = component.endsWith('.vue') || component.endsWith('.tsx');
    const startIndex = startFlag ? 0 : 1;
    const lastIndex = endFlag ? k.length : k.lastIndexOf('.');
    return k.substring(startIndex, lastIndex) === component;
  });

  if (matchKeys?.length === 1) {
    const matchKey = matchKeys[0];
    return defineAsyncComponent(dynamicViewsModules[matchKey])
  } else if (matchKeys?.length > 1) {
    console.warn(
      'Please do not create `.vue` and `.TSX` files with the same file name in the same hierarchical directory under the views folder. This will cause dynamic introduction failure'
    );
    stateValue.loading = false
    return;
  } else {
    stateValue.loading = false
    // warn('在src/views/下找不到`' + component + '.vue` 或 `' + component + '.tsx`, 请自行创建!');
    return EXCEPTION_COMPONENT;
  }
}

// 左侧树选择后触发
function onTreeSelect(key, node) {
  console.log('key, node', key, node);
  if (!node) {
    return
  }
  // stateValue.loading = true
  try {
    if (!node?.componentName || node?.componentName.toLowerCase() === 'layout' || node?.componentName === '' ) {
      selectNode.value = undefined
      return
    }
    
    stateValue.loading = true
    selectNode.value = {
      name: node?.title,
      path: node?.title + '_' + node?.componentName,
      component: dynamicImport(`${node?.componentName}`)
    }
  } catch(e) {
    console.error('error: ', e);
    stateValue.loading = false
  } finally {
    // clearTimeout(stateValue.timer)
  }
}

const handleQuerySuccess = () => {
  console.log('query success');
  stateValue.loading = false
}

const handleAddGroup = (node) => {
  openModal(true, { 
    isUpdate: false, 
    materialType: activeMaterialType.value, 
    record: { parentId: node.id }}
  )
}

const handleEditGroup = (node) => {
  openModal(true, { 
    isUpdate: true, 
    materialType: activeMaterialType.value, 
    record: { 
      ...node, 
      name: node.title
    }
  })
}

</script>

<style lang="less">
@import "./style.less";


</style>
